package com.zzxz.practicaltrainingsys.controller;

import com.zzxz.practicaltrainingsys.entity.*;
import com.zzxz.practicaltrainingsys.service.ProjectService;
import com.zzxz.practicaltrainingsys.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//查取所有的项目，获取项目列表。
@RestController
@RequestMapping("/Project")
@CrossOrigin
public class ProjectController {
    @Autowired
    private ProjectService projectService;

    @GetMapping("/List")
    public List<Project> getProjectList() {
        return projectService.getProject();
    }

    //获取所有项目名称
    @GetMapping("/names")
    public List<String> getProjectNames() {
        return projectService.getProjectNames();
    }

    //获取项目时间
    @GetMapping("/time")
    public Map<String, Object> getProjectTime(@RequestParam Integer projectId) {
        Map<String, Object> projectTime = projectService.getProjectTime(projectId);
        return projectTime;
    }

    @ApiOperation("添加项目信息")//增加项目功能
    @PostMapping("/insert")
    public int insertProject(@RequestBody Project project) {
        System.out.println("Received project: " +project);
        if (project == null) {
            throw new IllegalArgumentException("Project object cannot be null");
        }
        try {
            return projectService.insertProject(project);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
            throw new RuntimeException("Failed to insert project", e);
        }
    }

    //编辑更新项目
    @PostMapping("/update")
    public Map<String, Object> updateProject(@RequestBody Project project){
        System.out.println("=== 进入updateProject方法 ===");
        Map<String, Object> response = new HashMap<>();

        try{
            System.out.println("=== Controller 接收到的数据 ===");
            System.out.println("完整对象: " + project);
            System.out.println("项目ID: " + project.getProject_id()); // 使用下划线命名
            System.out.println("项目ID类型: " + (project.getProject_id() != null ? project.getProject_id().getClass().getName() : "null"));
            System.out.println("项目名称: " + project.getProject_name());

            // 检查关键字段是否为空
            if(project.getProject_id() == null){
                response.put("success", false);
                response.put("message", "项目ID为空，无法更新");
                return response;
            }

            // 先查询项目是否存在
            Project existingProject = projectService.getProjectById(project.getProject_id());
            if(existingProject == null){
                response.put("success", false);
                response.put("message", "未找到ID为 " + project.getProject_id() + " 的项目");
                return response;
            }

            System.out.println("找到现有项目: " + existingProject.getProject_name());

            int result = projectService.updateProject(project);
            System.out.println("更新结果: " + result);

            if(result > 0){
                response.put("success", true);
                response.put("message", "更新成功");
                response.put("affectedRows", result);
            } else {
                response.put("success", false);
                response.put("message", "更新失败，可能是数据没有变化或SQL执行失败");
            }

        }catch(Exception e){
            System.out.println("更新异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "更新异常: " + e.getMessage());
        }

        return response;
    }


    //删除项目
    @DeleteMapping("/delete")
    public int deleteProject(@RequestBody Project project) {
        return projectService.deleteProject(project);
    }


    //根据项目id查询该项目的项目信息
    @GetMapping("/find")
    public Project getProjectById(Integer project_id){
        return projectService.getProjectById(project_id);
    }

    //根据学校编号查询学校
    @GetMapping("/findschool")
    public School getSchoolById(Integer school_id){
        return projectService.getSchoolById(school_id);
    }
    // 根据学院编号查询学院信息
    @GetMapping("/findcollege")
    public College getCollegeById(Integer college_id){
        return projectService.getCollegeById(college_id);
    }

    //根据专业编号查询专业信息
    @GetMapping("/findmajor")
    public Major getMajorById(Integer major_id){
        return projectService.getMajorById(major_id);
    }

    //根据年级编号查询年级信息
    @GetMapping("/findgrade")
    public Grade getGradeById(Integer grade_id){
        return projectService.getGradeById(grade_id);
    }
    //根据老师id查所有项目信息
    @GetMapping("/find1")
    public List<Project> getProjectByTeacherId(Integer teacher_id){
        return projectService.getProjectByTeacherId(teacher_id);
    }
    //根据学校、学院、专业、年级查取所有项目信息
    @GetMapping("/byids")
    public List<Project> getProjectsByIds(@RequestParam("school_id") Integer school_id, Integer college_id, Integer major_id, Integer grade_id){
        return projectService.getProjectsByIds(school_id, college_id, major_id, grade_id);
    }

    // 获取当前正在实训的学生数量
    @GetMapping("/nowstudents")
    public Integer getNowStudents(){
        return projectService.getNowStudents();
    }
    @ApiOperation("图片/文件上传操作")
    @PostMapping("/upload")
    public String getPicFileName(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("File cannot be null or empty");
        }
        String oldFileName = file.getOriginalFilename();
        System.out.println("Old file name:" + oldFileName);
        String filePath = FileUtil.getUpLoadFilePath();
        String newFileName = System.currentTimeMillis() + oldFileName;


        try {
            FileUtil.uploadFile(file.getBytes(), filePath, newFileName);
            return newFileName;

        } catch (Exception e) {
            throw new RuntimeException("Failed to upload file", e);
        }



    }

    @GetMapping("/project/listByStudentInfo")
    public List<Project> getProjectsByStudentInfo(
            @RequestParam Integer school_id,
            @RequestParam Integer college_id,
            @RequestParam Integer major_id,
            @RequestParam Integer grade_id) {
        return projectService.getProjectsByStudentInfo(school_id, college_id, major_id, grade_id);
    }

    // 新增：获取所有项目，兼容前端 /project/all
    @GetMapping("/all")
    public List<Project> getAllProjects() {
        return projectService.getProject();
    }



}




